// topicList.js
const app = getApp()
import { requestApi } from '../../../api'
import { formatImage } from '../../../utils/formatImage'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    channel: '',
    start: 0,
    count: 20,
    loading: false,
    requestFlag: false, 
    topicData: [],
    noMore: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let channel = options.channel || 'wx_xcx'

    this.data.channel = channel
    this.getTopicData(channel)

    let systemInfo = {}

    try {
      systemInfo = wx.getSystemInfoSync()
    } catch (e) {
      // Do something when catch error
    }

    this.setData({
      winWidth: systemInfo.windowWidth,
      winHeight: systemInfo.windowHeight,
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  scrollAddTopic: function () {
    if (this.data.noMore) return false
    
    if (this.data.requestFlag) return false

    this.data.requestFlag = true

    this.getTopicData(this.data.channel)
  },

  toTopicDetail: function(e) {
    let tid = e.currentTarget.id
    let url = '../topicDetail/topicDetail?tid='+tid+'&start=0'

    wx.redirectTo({
      url: url,
    })
  },

  getTopicData: function(channel) {
    app.request({
      url: requestApi.topicListUrl,
	    login: false,
      data: {
        start: this.data.start,
        count: this.data.count,
        channel: channel
      },
    }, (data) => {
      let currentData = this.data.topicData
      let topicData = currentData.concat(data.original.data.item_list)
      let noMore

      if (data.original.data.item_list.length < 20) {
        noMore = true;
      }

      if (topicData.length) {
        for (let i = 0, len = topicData.length; i < len; i++) {
          if (topicData[i].data.banner_image.path) {
            topicData[i].data.banner_image.new_path = formatImage.cdnImage(topicData[i].data.banner_image.path, formatImage.THUMBNAIL_L)
            topicData[i].data.banner_image.padding_bottom = topicData[i].data.banner_image.height / topicData[i].data.banner_image.width * 100
          }
          if (topicData[i].data.author_image_uri && topicData[i].data.author_image_uri.length) {
            topicData[i].data.new_author_image_uri = formatImage.cdnImage(topicData[i].data.author_image_uri, formatImage.THUMBNAIL_XS)
          }
        }
      }

      this.setData({
        topicData: topicData,
        start: this.data.start + this.data.count,
        loading: true,
        noMore: noMore,
      })
    }, (error) => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      this.data.requestFlag = false
    })
  }
})